import {contentModel, messageModel} from "../mongodb/db";
import { Content, Message } from "../entities/content";

export class ContentServers {
    public static async add (content: {}): Promise<Content | string[]> {
        //将平面对象转换为content实体类
        const newObj = Content.transformerThis(content);
        //验证
        const validateArr = await newObj.validatorClass();
        //添加
        if(validateArr.length !== 0) {
            return validateArr;
        }

        return await contentModel.create(content)
    }

    public static async find(id: string) {
        return await contentModel.findById(id)
    }

    public static async findMore(m: {}) {
        // 将平面对象转换为movie实体类
        const newObj = Content.transformerThis(m);
        // 验证
        const validateArr = await newObj.validatorClass(true)
        // 添加
        if(validateArr.length !== 0) {
            return {
                err: validateArr,
                data: [],
                count: 0
            };
        };
        const queryData = await contentModel.find({
            class: {$regex: new RegExp(newObj.class)}
        }).sort({time: -1})
        const count = await contentModel.find({
            class: {$regex: new RegExp(newObj.class)}
        }).countDocuments();
        return {
            err: [],
            data: queryData,
            count
        }
   }

   public static async edit(id: string, content: {}) {
    //将平面对象转换为movie实体类
    const newObj = Content.transformerThis(content);
    //验证
    const validateArr = await newObj.validatorClass(true);
    //添加
    if(validateArr.length !== 0) {
        return validateArr;
    }
    return await contentModel.updateOne({_id: id}, content)
}
}

export class MessageServers {
    public static async add (message: {}) {
        //将平面对象转换为content实体类
        const newObj = Message.transformerThis(message);
        //验证
        const validateArr = await newObj.validatorClass();
        //添加
        if(validateArr.length !== 0) {
            return validateArr;
        }

        return await messageModel.create(message)
    }

    public static async find() {
        return await messageModel.find().sort({time: -1});
    }
}

